﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using Kugar.Core.ExtMethod;
using Kugar.Core.Web;
using Kugar.UI.Web.AdminLTE.Helpers;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageForms
{
    public  class PageForm_CustomContentField:PageForm_SingleInputFieldBase
    {
        private string _content = null;
        private bool _hasError = false;
        private string _errorMsg = "";
        private Predicate<string> _errorValidateName = null;
        private ControlBase _ctrl = null;

        public PageForm_CustomContentField(PageForm_Form form, ViewContext viewContext) : base(form, viewContext)
        {
            this.Css("webui-form_customcontentfield");
        }
        
        /// <summary>
        /// 使用指定name的错误信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public PageForm_CustomContentField WithNameError(string name)
        {
            _errorValidateName = (x)=>x==name;
            return this;
        }

        public PageForm_CustomContentField WithNameError(Predicate<string> checkErrorNames)
        {
            _errorValidateName =checkErrorNames;
            return this;
        }

        public PageForm_CustomContentField Content(Func<object, HelperResult> content)
        {
            _content = content(this).ToHtmlString();
            _ctrl = null;
            return this;
        }

        public PageForm_CustomContentField Content(ControlBase ctrl)
        {
            _ctrl = ctrl;
            _content = "";

            return this;
        }

        protected override void BeforeRender(TextWriter writer)
        {
            if (_errorValidateName != null && ViewContext.ModelState.Any(x => _errorValidateName(x.Key))) 
            {

                _errorMsg = ViewContext.ModelState.Where(x => _errorValidateName(x.Key)).SelectMany(x => x.Value.Errors)
                    .Select(x => x.ErrorMessage).JoinToString('|');
            }
            //ErrorMessage();
        
            
            base.BeforeRender(writer);
        }

        protected override string ErrorMessage
        {
            get
            {
                return _errorMsg;
            }
        }

        protected override void RenderContent(TextWriter writer)
        {
            //_content.WriteTo(writer,HtmlEncoder.Default);

            if (_ctrl!=null)
            {
                _ctrl.Render();
            }
            else
            {
                writer.WriteLine(_content);
            }
            

            
        }
    }
}
